<template>
  <jke-modal
    :visible.sync="jkeForm.visible"
    :width="1200"
    :title="jkeForm.title"
    :fullscreen.sync="jkeForm.fullscreen"
    :switchFullscreen="jkeForm.switchFullscreen"
  >
    <!--  -->
    <crumbs
      @goBack="goBack"
      :superiorMenu="['设备管理', '设备保养', '保养任务']"
      marginBottom="10px"
      currentMenu="保养汇报"
    ></crumbs>
    <div class="uni-card">
      <div class="bd-line"></div>
      <div class="item-wrap">
        <div class="detail-item">
          <p class="subtitle">任务编号</p>
          <p class="secondary-text">{{ detailInfo.taskCode || '-' }}</p>
        </div>
        <div class="detail-item">
          <p class="subtitle">保养设备</p>
          <p class="secondary-text">
            {{ detailInfo.deviceCode || '-' }}<i v-if="detailInfo.deviceCode && detailInfo.deviceName">- </i
            >{{ detailInfo.deviceName || '-' }}
          </p>
        </div>
        <div class="detail-item">
          <p class="subtitle">设备类别</p>
          <p class="secondary-text">{{ detailInfo.deviceCategoryText || '-' }}</p>
        </div>
      </div>
    </div>
    <div class="form-body">
      <a-card title="点巡检项目" :bordered="false" style="margin-top: 12px">
        <j-editable-table
          ref="goodsTable"
          :loading="goodsTable.loading"
          :columns="goodsTable.columns"
          :dataSource="goodsTable.dataSource"
          :maxHeight="300"
          :rowNumber="true"
          :actionButton="true"
          :addActionButton="false"
          @valueChange="valueChange"
        >
        </j-editable-table>
      </a-card>
      <a-card title="其他信息" :bordered="false" style="margin-top: 12px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="备注" style="flex: 1">
            <a-textarea placeholder="请输入" :maxLength="500" auto-size v-decorator="['remark']" />
          </a-form-item>
        </a-form>
        <a-form layout="vertical">
          <a-form-item label="附件" style="flex: 1">
            <file-upload :ids="attachment" @getFileList="getFileList"></file-upload>
            <p style="line-height: 30px;color:#8d8d8d;">最多上传5个文件，每个大小不可超过20M</p>
          </a-form-item>
        </a-form>
      </a-card>
    </div>
    <div class="footer-submit form-footer">
      <a-button type="primary" :loading="loadingSubmit" @click="handleSubmit()"> 提交 </a-button>
    </div>
  </jke-modal>
</template>
<script>
import crumbs from '@/components/crumbs.vue'
import FileUpload from '@/components/fileActions/FileUpload.vue'
import { APILX } from '@/api/requestLx'
import { API } from '@/api/requestFzs'
import moment from 'dayjs'
import JEditableTable from '@/components/jeecg/JEditableTable.vue'
import { validateTables, FormTypes, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
import { fourFloatNum, validateDuplicateValue, checkPrice } from '@/utils/util'
import tableSelect from '@/components/tableSelect'
import { maintenanceDetail, maintenanceTaskReport } from '@/api/erpApi'
export default {
  data() {
    return {
      jkeForm: {
        title: '保养汇报',
        visible: false,
        fullscreen: true,
        switchFullscreen: true,
      },
      detailInfo: '',
      validateDuplicateValue,
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'coordinated' }),
      attachment: '',
      submitApi: API.erpSaleContractAdd,
      isEdit: false,
      loadingSubmit: false,
      customSelectList: [],
      goodsTable: {
        loading: false,
        dataSource: [{}],
        columns: [
          {
            title: '项目Id',
            key: 'itemId',
            type: FormTypes.hidden,
          },
          {
            title: '项目编号',
            key: 'projectCode',
            type: FormTypes.hidden,
          },

          {
            title: '保养项',
            key: 'projectNameCode',
            type: FormTypes.normal,
            ellipsis: true,
            //  customRender: (text, record, index) => `${record.projectCode?record.projectCode:''}---`,
          },
          {
            title: '保养标准',
            key: 'maintainStandard',
            type: FormTypes.normal,
          },
          {
            title: '保养描述',
            key: 'maintainDescribe',
            // width: '18%',
            type: FormTypes.input,
            isrequired: true,
            /* options: [
              // 下拉选项
              { title: '正常', value: '0' },
              { title: '异常', value: '1' },
            ], */
            allowInput: true,
            defaultValue: '',
            placeholder: '请输入',
            validateRules: [{ required: true, message: '请输入' }],
          },
        ],
      },
      queryId: '', // 校验编号唯一ID
      allGoods: [],
      goodsProps: {},
      selectIndex: 0,
      selectColumns: [
        {
          title: '商品编号',
          align: 'center',
          dataIndex: 'goodsCode',
        },
        {
          title: '商品名称',
          align: 'center',
          dataIndex: 'goodsName',
        },
        {
          title: '规格',
          align: 'center',
          dataIndex: 'spec',
        },
      ],
      filterForm: {},
    }
  },
  components: {
    FileUpload,
    crumbs,
    JEditableTable,
    tableSelect,
  },
  methods: {
    valueChange() {},
    // 重置
    searchResetGoods() {
      this.filterForm = {}
      this.$refs.tableSelect.searchReset()
    },
    // 筛选
    searchGoods() {
      this.$refs.tableSelect.searchQuery(this.filterForm)
    },
    // 点击选择商品下拉框，弹出选择组件
    showSelect(p) {
      this.goodsProps = p
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [this.goodsProps.rowId] })
        .values[0]
      let par = {
        list: '/wms/goods/getAllGoodsBaseInfo',
        visible: true, //弹窗开启
        title: '商品', //标题名称
        multi: false, //是否多选
        columns: this.selectColumns, //表格配置
        value: tableValue.goodsId || '', //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: tableValue.goodsName || '', //回显的中文，如：'张三'
        textKey: 'goodsName', //回显的中文key
      }
      this.$refs.tableSelect.getInit(par)
    },
    // 选择商品回调
    getSelectValue(id, text, item, p) {
      this.selectIndex += 1 //重置组件去除表格默认勾选数据，让自己赋值的数据回显（重要！！！）
      if (!id) {
        this.$refs.goodsTable.setValues([
          {
            rowKey: this.goodsProps.rowId, // 行的id
            values: {
              // 在这里 values 中的 goodsId 是你 columns 中配置的 key
              goodsId: '',
              goodsName: '',
              goodsCode: '',
              spec: '',
              basicUnit: '',
              unit: '',
              unitList: '',
              projectCode: '',
            },
          },
        ])
        return
      }
      this.$refs.goodsTable.setValues([
        {
          rowKey: this.goodsProps.rowId, // 行的id
          values: {
            // 在这里 values 中的 goodsId 是你 columns 中配置的 key
            goodsId: id,
            goodsName: text,
            goodsCode: item[0].goodsCode,
            spec: item[0].spec,
            projectCode: item[0].projectCode,
          },
        },
      ])
      this.setGoodsInfo(id, p)
      console.log(id, text, item, this.goodsProps.rowId, '列表选择的数据')
    },
    // 根据选择的商品带出其他商品信息并填充
    setGoodsInfo(value, p) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false }).values
      var newArr = []
      tableValue.forEach((v) => {
        newArr.push(v.goodsId)
      })
      var newArrLen = [...new Set(newArr)].length
      var oldArrLen = tableValue.length
      if (newArrLen < oldArrLen) {
        this.$refs.goodsTable.removeRows(this.goodsProps.rowId)
        this.$antdMessage.warning('该商品已存在，请直接修改数据')
        return
      }
      API.findUnitListByGoodsId({ goodsId: value }).then((res) => {
        // this.allGoods.push({
        //   goodsId: value,
        //   unitList: res.result
        // })
        var unitObj = res.result.find((u) => u.unitType == 'basic_unit')
        this.$refs.goodsTable.setValues([
          {
            rowKey: this.goodsProps.rowId, // 行的id
            values: {
              // 在这里 values 中的 specifications 是你 columns 中配置的 key
              basicUnit: 'basic_unit',
              unit: unitObj.unit || '',
              unitId: unitObj.id,
              unitList: JSON.stringify(res.result),
            },
          },
        ])
      })
    },
    /* 面包屑返回 */
    goBack() {
      // this.$router.push('/devicesCare/maintenanceTasksList')
      this.jkeForm.visible = false
    },
    /* 获取编辑详情 */
    initForm(id) {
      this.jkeForm.visible = true
      if (id) {
        this.queryId = id
        maintenanceDetail({ id: id }).then((res) => {
          if (res.code == 200) {
            this.detailInfo = res.result
            console.log(this.detailInfo, '---maintenanceDetail')
            let editForm = res.result
            editForm.signUserCode = editForm.signUserCode
            this.$nextTick(() => {
              this.form.setFieldsValue(editForm)
            })
            this.attachment = res.result.attachment
            let newGoodsList = res.result.itemList
            this.goodsTable.dataSource = newGoodsList.map((v) => {
              v.projectNameCode = v.projectCode + '-' + v.projectName
              return v
            })
          }
        })
        /* APILX.messDeviceCheckTaskQueryById(id).then((res) => {
          if (res.code == 200) {
            this.detailInfo = res.result
            let editForm = res.result
            editForm.signUserCode = editForm.signUserCode
            this.$nextTick(() => {
              this.form.setFieldsValue(editForm)
            })
            this.attachment = res.result.attachment
            let newGoodsList = res.result.itemList
            // for (let i = 0; i < newGoodsList.length; i++) {
            //   const good = newGoodsList[i]
            //   good.basicUnit = good.unitType
            //   good.unitList = JSON.stringify(good.unitList)
            // }
            // this.allGoods = newGoodsList
            this.goodsTable.dataSource = newGoodsList
            console.log(newGoodsList)
          }
        }) */
      } else {
      }
    },
    /* 获取附件 */
    getFileList(v) {
      this.attachment = v
      console.log('上传的附件id：', v)
    },
    // 提交（必须使用名为submitProcess方法进行提交）
    submitProcess(e) {
      if (this.isEdit) {
        this.handleSubmit()
      } else {
        if (e.nodeDtos) {
          // 获取到数据后写表单提交的方法
          this.handleSubmit(e)
        } else {
          // 调用子组件的方法获取数据
          this.$refs.examine.confirm()
        }
      }
    },
    handleSubmit() {
      let errArr = []
      let parameters = {}
      let formData = {}
      let { error, values } = this.$refs.goodsTable.getValuesSync({ validate: true })
      if (error === 0) {
      } else {
        errArr.push(false)
      }
      this.form.validateFields((err, formValues) => {
        if (!err) {
          parameters = { ...formValues, attachment: this.attachment }
          if (this.isEdit) {
            parameters.id = this.queryId
          } else {
          }
          if (errArr.length == 0) {
            let messDeviceMaintainTaskItem = values.map((g, i) => {
              return {
                maintainStandard: g.maintainStandard,
                projectCode: g.projectCode,
                projectName: g.projectName,
                maintainDescribe: g.maintainDescribe,
                itemId: g.itemId,
                id: g.id,
              }
            })
            parameters.id = this.detailInfo.id
            //  parameters.remark = this.form.remark;
            parameters.messDeviceMaintainTaskItem = messDeviceMaintainTaskItem
            parameters.signUserId = this.userId
            console.log(this.form, parameters, '---parameters')
            this.loadingSubmit = true
            maintenanceTaskReport(parameters).then((res) => {
              this.loadingSubmit = false
              if (res.code == 200) {
                // let subMsg = this.isEdit ? '保养汇报成功' : '保养汇报成功'
                this.$antdMessage.success('保养汇报成功')
                this.$emit('refresh')
                this.goBack()
              } else {
                this.$antdMessage.error(res.message)
              }
            })
          }
        } else {
        }
      })
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
/deep/.ant-form-vertical {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  .ant-form-item {
    width: 30%;
  }
}
.form-body {
  height: calc(100vh - 188px);
  overflow-y: scroll;
}
.form-footer {
  margin: 12px -12px 0 -12px;
}
.code-btn {
  position: absolute;
  right: 0;
  top: -34.5px;
}
.item-wrap {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}
.item-wrap:nth-of-type(n + 3) {
  margin-top: 40px;
}
.detail-item {
  width: 30%;
}
.uni-card {
  padding: 24px 40px;
  margin: -12px -12px 0;
  background: #fff;
}
.bd-line {
  height: 1px;
  background: @greyBorder;
  margin: -12px 0 24px -40px;
}
.cards-box {
  height: calc(100vh - 219px);
  overflow-y: scroll;
}
</style>
